package com.le.tester.sevice.impl;

import com.le.tester.dao.UserInfoDao;
import com.le.tester.dto.UserRegisterDto;
import com.le.tester.sevice.UserService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * createTime：2025-03-19 16:14
 * description：用户业务逻辑实现
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    public UserInfoDao userInfoDao;

    @Autowired
    public RedissonClient redissonClient;

    public String register(UserRegisterDto userRegisterDto) {

        //RLock lock = redissonClient.getLock("lock" + userRegisterDto.getPhone());
        //替换成多把锁
        RLock lock = redissonClient.getMultiLock(redissonClient.getLock("lock" + userRegisterDto.getPhone()),
                redissonClient.getLock("lock" + userRegisterDto.getName()));
        lock.lock();
        try {
            //phone check
            int phoneCount = userInfoDao.selectPhone(userRegisterDto.getPhone());
            if (phoneCount > 0) {
                return "手机号已经存在";
            }

            int nameCount = userInfoDao.selectName(userRegisterDto.getName());
            if (nameCount > 0) {
                return "用户名已经存在";
            }
            //insert into user info
            userInfoDao.register(userRegisterDto);
            return "注册成功";
        } finally {
            lock.unlock();
        }


    }
}
